package com.scenery.services;

import java.util.ArrayList;

import net.hainan.chat.Openfire;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.jivesoftware.smack.ConnectionConfiguration;
import org.jivesoftware.smack.PacketCollector;
import org.jivesoftware.smack.SASLAuthentication;
import org.jivesoftware.smack.SmackConfiguration;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.filter.AndFilter;
import org.jivesoftware.smack.filter.PacketFilter;
import org.jivesoftware.smack.filter.PacketIDFilter;
import org.jivesoftware.smack.filter.PacketTypeFilter;
import org.jivesoftware.smack.packet.IQ;
import org.jivesoftware.smack.packet.Presence;
import org.jivesoftware.smack.packet.Registration;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.util.Log;
import android.widget.Toast;

import com.scenery.Constans;
import com.scenery.util.HttpUtil;
import com.scenery.vo.User;

public class UserServices {
	private static String tag = UserServices.class.getName();
	private String ip = "";
	private int ofport=5222,
			webport=8080;
	Context context;
	public UserServices(){
		
	}
	public UserServices(Context context){
		this.context=context;
	}
	
	public int getOfport() {
		return ofport;
	}
	public void setOfport(int ofport) {
		this.ofport = ofport;
	}
	public int getWebport() {
		return webport;
	}
	public void setWebport(int webport) {
		this.webport = webport;
	}
	public String getIp() {
		return ip;
	}

	public void setIp(String ip) {
		this.ip = ip;
	}
	private IQ result;
	/*** 用户注册OpenFire */
	public String registerOpenFire(String username, String password) {
		Log.d(tag, "registerOpenFire");
		String ret = "-1";
		ConnectionConfiguration config = new ConnectionConfiguration(ip, 5222);
		Openfire.oConnection = new XMPPConnection(config);
		try {
			Openfire.oConnection.connect();
			Log.d(tag, ""+Openfire.oConnection.getServiceName());
			Registration reg = new Registration();// 新建注册类
			reg.setType(IQ.Type.SET);
			reg.setTo(Openfire.oConnection.getServiceName());
			reg.setUsername(username);
			reg.setPassword(username);
			reg.addAttribute("android", "geolo_createUser_android");
			System.out.println("reg:" + reg);
			PacketFilter filter = new AndFilter(new PacketIDFilter(reg
					.getPacketID()), new PacketTypeFilter(IQ.class));
			PacketCollector collector = Openfire.oConnection.createPacketCollector(filter);
			Openfire.oConnection.sendPacket(reg);

			result = (IQ) collector.nextResult(SmackConfiguration
					.getPacketReplyTimeout());
			//Log.d(tag, "result:"+result.getType().RESULT.);
			if (result == null) {
//				Toast.makeText(context, "没有返回结果",
//						Toast.LENGTH_SHORT).show();
				Log.d(tag, "没有返回结果"+result);
				ret = "4";
			} else if (result.getType() == IQ.Type.ERROR) {
				if (result.getError().toString().equalsIgnoreCase(
						"conflict(409)")) {
//					Toast.makeText(context, "账号已存在",
//							Toast.LENGTH_SHORT).show();
					Log.d(tag, "账号已存在"+result);
					ret = "4";
				} else {
//					Toast.makeText(context, "注册失败",
//							Toast.LENGTH_SHORT).show();
					ret = "4";
					Log.d(tag, "注册失败"+result);
				}
			} else if (result.getType() == IQ.Type.RESULT) {
//				Toast.makeText(context, "恭喜你注册成功",
//						Toast.LENGTH_SHORT).show();
				Log.d(tag, "恭喜你注册成功"+result);
				ret = "0";
			}
		} catch (XMPPException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			Log.d(tag, "连接服务器异常"+result);
			ret = "4";
//			Toast.makeText(context, "连接服务器异常",
//					Toast.LENGTH_SHORT).show();
		}
		
		

		return ret;

	}

	/*** 用户登陆 OpenFire
	 * 
	 *  当使用asmack登陆jabberd2时.会发生错误:

SASL authentication failed using mechanism DIGEST-MD5

意思大概是登陆时使用了DIGEST-MD5身份验证机制.而jabberd2服务器并没有开启.所以会发生错误.

解决办法是在login之前加入:SASLAuthentication.supportSASLMechanism("PLAIN", 0);

http://kongweile.iteye.com/blog/1154394

http://06peng.com/read.php/88.htm
	 *  
	 *  */
	public String loginOpenFire(String username, String password) {
		Log.d(tag, "loginOpenFire:" + username + password + ",ip:" + ip);
		String ret = "-1";
		

		ConnectionConfiguration config = new ConnectionConfiguration(ip, 5222);
		// Connection connection = new XMPPConnection(config);
		SASLAuthentication.supportSASLMechanism("DIGEST-MD5", 0);


		try {
			config.setSecurityMode(ConnectionConfiguration.SecurityMode.enabled); 
			config.setSASLAuthenticationEnabled(true);      
			config .setTruststorePath("/system/etc/security/cacerts.bks");       
			config.setTruststorePassword("changeit");       
			config.setTruststoreType("bks"); 
			
			Openfire.oConnection = new XMPPConnection(config);

			Openfire.oConnection.connect();
			//SASLAuthentication.supportSASLMechanism("PLAIN", 0);
			//Openfire.oConnection.login(username, password);
			Openfire.oConnection.login(username, password, "resource");
			Openfire.oCurrentAccount = username;
			Presence presence = new Presence(Presence.Type.available);
			Openfire.oConnection.sendPacket(presence);
			// Openfire.oUtil.saveString("login_account", username);
			// Openfire.oUtil.saveString("login_password", password);

			ret = "1";

		} catch (XMPPException e) {
			// TODO Auto-generated catch block
			Log.e(username, e.getLocalizedMessage());
			e.printStackTrace();
			ret = "4";
		}catch(Exception e) {
			// TODO Auto-generated catch block
			Log.e(username, e.getLocalizedMessage());
			e.printStackTrace();
			ret = "4";
		}

		return ret;

	}

	public static String register(String username, String password) {
		Log.d(tag, "register");
		int ret = -1;
		ArrayList<NameValuePair> parameters = new ArrayList<NameValuePair>();
		parameters.add(new BasicNameValuePair("action", "regist"));
		parameters.add(new BasicNameValuePair("userid", username));
		parameters.add(new BasicNameValuePair("password", password));
		String json = HttpUtil.httpPost(parameters, Constans.USER_URL);
		Log.d(tag, "ret:" + json);
		// if(!json.endsWith(null))
		// {
		// ret=Integer.parseInt(json);
		// }
		return json;

	}

	public static String login(String username, String password) {
		Log.d(tag, "register" + username + password);

		int ret = -1;
		ArrayList<NameValuePair> parameters = new ArrayList<NameValuePair>();
		parameters.add(new BasicNameValuePair("action", "login"));
		parameters.add(new BasicNameValuePair("userid", username));
		parameters.add(new BasicNameValuePair("password", password));
		String json = HttpUtil.httpPost(parameters, Constans.USER_URL);
		Log.d(tag, "ret:" + json);
		// if(json!="")
		// {
		// ret=new Integer(json);
		// }

		return json;

	}
	public  String postLoation(String userid,String lon,String lat)
	{
		Log.d(tag, "postLoation");
		ArrayList<NameValuePair> parameters = new ArrayList<NameValuePair>();
		parameters.add(new BasicNameValuePair("action", "location"));// userid
		parameters.add(new BasicNameValuePair("userid", userid));
		parameters.add(new BasicNameValuePair("lon", lon));
		parameters.add(new BasicNameValuePair("lat", lat));
		String json = HttpUtil.httpPost(parameters, "http://"+ip+":"+webport+Constans.USER_URL);
		return json;
	}
	/****
	 * 查看好友位置
	 * **/
	public  ArrayList<User> friend(String userid) {
		ArrayList<User> list = new ArrayList<User>();

		// String json=HttpUtil.httpRequestInfo(
		// Constans.scenery_bycity_URL+cityId);
		ArrayList<NameValuePair> parameters = new ArrayList<NameValuePair>();
		parameters.add(new BasicNameValuePair("action", "friend"));// userid
		parameters.add(new BasicNameValuePair("userid", userid));
		String json = HttpUtil.httpPost(parameters, "http://"+ip+":"+webport+Constans.USER_URL);
		Log.d(tag, "getSceneryList json:" + json);

		try {
			JSONObject jo = new JSONObject(json);

			if (jo.getString("code").equals("100")) {
				JSONArray array = jo.getJSONArray("list");
				for (int i = 0; i < array.length(); i++) {
					JSONObject rs = array.getJSONObject(i);
					User bean = new User();
					Log.d(tag,"lat:"+ rs.getString("lat")+",lon:"+rs.getString("lat"));
					bean.setUserId(rs.getString("userId"));
					bean.setLon(rs.getString("lon"));
					bean.setLat(rs.getString("lat"));
					list.add(bean);
				}
			}

		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		Log.d(tag, "list size:" + list.size());
		return list;
	}
}
